package com.kosinsut.youtubeplaylistbuilder.playlistbuilder;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import com.google.gdata.client.youtube.YouTubeQuery;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.VideoFeed;
import com.google.gdata.util.ServiceException;
import com.kosinsut.youtubeplaylistbuilder.Song;

/**
 * MVVideoSearch is the default VideoSearcher it will use the song's name and artist to do the relevance search.
 * @author Kosin
 *
 */
public class MVVideoSearcher implements VideoSearcher {

	@Override
	public VideoEntry searchVideoEntry(YouTubeService service, Song song) throws PlaylistBuilderException {
		try {
			YouTubeQuery query = new YouTubeQuery(new URL("http://gdata.youtube.com/feeds/api/videos"));	
			
			
			String searchString = song.getName()+" "+song.getArtist();
			
			query.setOrderBy(YouTubeQuery.OrderBy.RELEVANCE);
			query.setFullTextQuery(searchString);
			query.setSafeSearch(YouTubeQuery.SafeSearch.NONE);
			
			
			VideoFeed videoFeed = service.query(query, VideoFeed.class);
			List<VideoEntry> videoEntryList = videoFeed.getEntries();
			
			
			if (videoEntryList.size() > 0) {
				return videoEntryList.get(0);
			} else {
				System.out.println("Video not found: "+searchString);
				
				System.out.println("Trying new text");
				query.setFullTextQuery(song.getName());
				VideoFeed retryVideoFeed = service.query(query, VideoFeed.class);
				List<VideoEntry> retryVideoEntryList = retryVideoFeed.getEntries();
				if (retryVideoEntryList.size() > 0) {
					return retryVideoEntryList.get(0);
				}
				
				throw new PlaylistBuilderException("Video not found: "+searchString); 
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new PlaylistBuilderException("Cannot search a video");
		} catch (ServiceException e) {
			e.printStackTrace();
			throw new PlaylistBuilderException("Cannot search a video");
		} 

	}

}
